#pragma once
#include <iostream>
#include <string>
#include <unordered_map>
#include <fstream>
#include "Log.hpp"

using namespace log_ns;

const std::string sep = ": ";

class Dict {
    void LoadDict(const std::string& path) {
        std::ifstream in(path);
        if (!in.is_open()) {
            LOG(FATAL, "load the dictionary failed\n");
            exit(0);
        }
        LOG(DEBUG, "open the dictionary success\n");
        // 将数据加载到map中
        std::string info;
        while (std::getline(in, info)) {
            if (info.empty()) continue;
            size_t pos = info.find(sep);
            if (pos == std::string::npos) continue;
            // 现在将获取出来的字符串分隔开
            std::string key = info.substr(0, pos);
            std::string value = info.substr(pos + sep.size());
            if (key.empty() || value.empty()) continue;

            // 走到这里就是正常可以加载的数据
            LOG(DEBUG, "load the info: %s\n", info.c_str());
            _dict.insert(std::make_pair(key, value));
        }

        LOG(DEBUG, "load the dictionary success\n");
        
        in.close();
    }
public:
    Dict(const std::string& path) : _dict_path(path)
    {
        LoadDict(_dict_path);
    }

    std::string Translate(const std::string& word) {
        if (word.empty() || !_dict.count(word))
            return "None";
        return _dict[word];
    }

    ~Dict() {}
private:
    std::string _dict_path;
    std::unordered_map<std::string, std::string> _dict;
};